package com.example.service;

import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Service;

import com.example.constant.BodyTypeConstant;
import com.example.container.ChargingPileContainer;
import com.example.entity.ChargingPile;
import com.example.entity.body.Body;
import com.example.entity.body.impl.InitBody;
import com.example.entity.factory.Unpooled;
import com.example.entity.message.Message;
import com.example.util.DecodeUtil;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

/**
 * 处理接收到的握手报文
 * 
 * @author yao
 *
 */

@Service
public class ShakeHandHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		// 错误报文丢弃导致
		if (msg == null) {
			return;
		}
		Message message = (Message) msg;

		Body body = message.getBody();
		// 判断是否初始报文(初始报文有别于规范，特殊处理)
		if ((body == null) || (body != null && body.getBodyType() == BodyTypeConstant.ASDU)) {
			ctx.fireChannelRead(msg);
		} else if (body.getBodyType() == BodyTypeConstant.INIT) {
			System.out.println("调用握手");
			System.out.println("IP 地址是： " + ctx.channel().remoteAddress());
			InitBody initBody = message.getBody();

			long equipmentId = initBody.getEquipmentID();
			String id = DecodeUtil.BCDDecode(equipmentId);

			// 容器操作
			ChargingPileContainer container = ChargingPileContainer.getInstance();
			ChargingPile state = container.get(id);
			if (state == null) {
				state = new ChargingPile(ctx);
				// 数据库操作
				container.push(id, state);
			}

			// session保存
			AttributeKey<ChargingPile> key1 = AttributeKey.valueOf("state");
			ctx.channel().attr(key1).set(state);
			// id保存
			AttributeKey<String> key2 = AttributeKey.valueOf("id");
			ctx.channel().attr(key2).set(id);

			state.hasInit();

			ChannelFuture channelFuture = ctx.writeAndFlush(message);

			channelFuture.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					// 一秒后发送U帧3
					ctx.channel().eventLoop().schedule(new Runnable() {

						@Override
						public void run() {
							ctx.writeAndFlush(Unpooled.newUMessage3());
						}
					}, 3, TimeUnit.SECONDS);
				}
			});

		}

	}
}
